//
//  ChatWebScoket.swift
//  Exchange
//
//  Created by rui on 2018/6/21.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
import Starscream

@objc protocol ChatScoketDelegate {
    ///返回是否使用
    @objc optional func webSocket(didReadOrderMsg data: [String:Any]) -> Bool
    @objc optional func webSocket(didReadOrderHistoryMsg data: [String:Any])
    ///返回是否使用
    @objc optional func webSocket(didReadAdMsg data: [String:Any]) -> Bool
    @objc optional func webSocket(didReadAdHistoryMsg data: [String:Any])
}

class ChatWebScoket {
    
    public static let  kTimeDifference = "chat_timeDifference"

    var scoket:WebSocket?
    weak var delegate:ChatScoketDelegate?
    var reConnectTime:TimeInterval = 0
    
    ///服务器和本地时间差
    var timeDifference: Double? {
        return AppCacheInfo.default.object(forKey: ChatWebScoket.kTimeDifference) as? Double
    }
    
    static let manager  = ChatWebScoket()

    init() {
       connectServer()
    }
    
    ///登陆
    func login() {
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
//            self.sendMsg(req: ChatReq(cmd: .login))
//        }
    }

    func sendMsg(req: ChatReq)  {
        if let reqStr = req.req {
            self.scoket?.write(string: reqStr)
        }
    }

    private func connectServer() {
        let server = ServerFactory.default.server(identifier: Service.webSocket)
        if let url = URL(string: server.baseurl) {
            self.scoket = WebSocket(url: url)
            self.scoket?.delegate = self
            self.scoket?.connect()
        }else {
            fatalError("聊天websocket地址错误")
        }
    }
 
    func reCounnect() {
        self.scoket?.disconnect()
        if (reConnectTime > 64) {
            //您的网络状况不是很好，请检查网络后重试
            reConnectTime = 0
            return;
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2*reConnectTime, execute: {
            self.connectServer()
        })
        if reConnectTime == 0 {
            reConnectTime = 2
        }else {
            reConnectTime = reConnectTime*2
        }
    }
}

extension ChatWebScoket: WebSocketDelegate {
    //MARK: - WebSocketDelegate
    func websocketDidConnect(socket: WebSocketClient) {
        reConnectTime = 0
    }
    
    func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
        reCounnect()
    }
    
    func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
        guard let res =  text.jsonObject as? [String:Any] ,let cmdStr = res["cmd"] as? String,let contentStr = res["content"] as? String  else {
            return
        }
        if cmdStr != "c2c_chat" {
            return
        }
        guard let content = contentStr.jsonObject as? [String:Any] else { return }

        guard let method = content["method"] as? String,let data = content["data"]  as? [String:Any] else { return }

        let cmdType = ChatReq.CmdType(rawValue: method)
        
        if cmdType == .ad {
            let isUsed = self.delegate?.webSocket?(didReadAdMsg: data) ?? false
            if !isUsed {
                ///发送通知
            }
        }else if cmdType == .adHistory {
            self.delegate?.webSocket?(didReadAdHistoryMsg: data)
        }else if cmdType == .order {
            let isUsed = self.delegate?.webSocket?(didReadOrderMsg: data) ?? false
            if !isUsed {
                ///发送通知
            }
        }else if cmdType == .orderHistory {
            self.delegate?.webSocket?(didReadOrderHistoryMsg: data)
        }
        
    }
    
    func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
        dPrint(data)
    }
}
